package giftmail.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import giftmail.dao.DataMapper;
import giftmail.model.Data;

@Service("dataService")
@CacheConfig(cacheNames = { "dataCache" })
@Transactional
public class DataServiceImpl implements IDataService {

	@Autowired
	private DataMapper dataMapper;

	/**
	 * redis操作： 查看Data表List
	 * 
	 * 2017-08-30 补充:此方案不适合业务场景(不能做所有List数据的缓存方案,弃)
	 * 
	 * @author demo
	 */
	@Cacheable(key = "'data:'+#id", unless = "#result == null")
	@Override
	public List<Data> findData() {
		List<Data> findData = dataMapper.findData();
		if (findData != null && findData.size() > 0) {
			for (Data data : findData) {
				Integer id = data.getId();
				String name = data.getName();
				System.out.println(id);
				System.out.println(name);
			}
			return findData;
		}
		return null;

	}

	/**
	 * 根据id查询数据 同时:插入redis
	 */
	@Cacheable(key = "'data:'+#id", unless = "#result == null")
	@Override
	public Data getById(int id) {
		Data findDataById = dataMapper.findDataById(id);
		if (findDataById != null) {
			return findDataById;
		}
		return null;
	}

	/**
	 * 用户数据 同时:删除redis
	 */
	@CacheEvict(key = "'data:'+#data.id")
	@Override
	public void update(Data data) {
		Integer id = data.getId();
		Data selectByPrimaryKey = dataMapper.selectByPrimaryKey(id);
		if (selectByPrimaryKey != null) {
			selectByPrimaryKey.setName(data.getName());
			selectByPrimaryKey.setDescripe(data.getDescripe());
			selectByPrimaryKey.setUrl(data.getUrl());
		}
		dataMapper.update(selectByPrimaryKey);

	}

}
